Adding a bunch of hooks from wikiHow into DifferenceEngine, 2nd try
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.js
1 /**
2 * Base library for MediaWiki.
3 *
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
5 *
6 * @class mw
7 * @alternateClassName mediaWiki
8 * @singleton
9 */
10 /*jshint latedef:false */
11 ( function ( $ ) {
12 'use strict';
13
14 var mw,
15 hasOwn = Object.prototype.hasOwnProperty,
16 slice = Array.prototype.slice,
17 trackCallbacks = $.Callbacks( 'memory' ),
18 trackHandlers = [],
19 trackQueue = [];
20
21 /**
22 * FNV132 hash function
23 *
24 * This function implements the 32-bit version of FNV-1.
25 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
26 * its output is base 36 rather than hex.
27 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
28 *
29 * @private
30 * @param {string} str String to hash
31 * @return {string} hash as an seven-character base 36 string
32 */
33 function fnv132( str ) {
34 /*jshint bitwise:false */
35 var hash = 0x811C9DC5,
36 i;
37
38 for ( i = 0; i < str.length; i++ ) {
39 hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
40 hash ^= str.charCodeAt( i );
41 }
42
43 hash = ( hash >>> 0 ).toString( 36 );
44 while ( hash.length < 7 ) {
45 hash = '0' + hash;
46 }
47
48 return hash;
49 }
50
51 /**
52 * Create an object that can be read from or written to from methods that allow
53 * interaction both with single and multiple properties at once.
54 *
55 * @example
56 *
57 * var collection, query, results;
58 *
59 * // Create your address book
60 * collection = new mw.Map();
61 *
62 * // This data could be coming from an external source (eg. API/AJAX)
63 * collection.set( {
64 * 'John Doe': 'john@example.org',
65 * 'Jane Doe': 'jane@example.org',
66 * 'George van Halen': 'gvanhalen@example.org'
67 * } );
68 *
69 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
70 *
71 * // You can detect missing keys first
72 * if ( !collection.exists( wanted ) ) {
73 * // One or more are missing (in this case: "Daniel Jackson")
74 * mw.log( 'One or more names were not found in your address book' );
75 * }
76 *
77 * // Or just let it give you what it can. Optionally fill in from a default.
78 * results = collection.get( wanted, 'nobody@example.com' );
79 * mw.log( results['Jane Doe'] ); // "jane@example.org"
80 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
81 *
82 * @class mw.Map
83 *
84 * @constructor
85 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
86 * empty object.
87 * For backwards-compatibility with mw.config, this can also be `true` in which case values
88 * are copied to the Window object as global variables (T72470). Values are copied in
89 * one direction only. Changes to globals are not reflected in the map.
90 */
91 function Map( values ) {
92 if ( values === true ) {
93 this.values = {};
94
95 // Override #set to also set the global variable
96 this.set = function ( selection, value ) {
97 var s;
98
99 if ( $.isPlainObject( selection ) ) {
100 for ( s in selection ) {
101 setGlobalMapValue( this, s, selection[ s ] );
102 }
103 return true;
104 }
105 if ( typeof selection === 'string' && arguments.length ) {
106 setGlobalMapValue( this, selection, value );
107 return true;
108 }
109 return false;
110 };
111
112 return;
113 }
114
115 this.values = values || {};
116 }
117
118 /**
119 * Alias property to the global object.
120 *
121 * @private
122 * @static
123 * @param {mw.Map} map
124 * @param {string} key
125 * @param {Mixed} value
126 */
127 function setGlobalMapValue( map, key, value ) {
128 map.values[ key ] = value;
129 mw.log.deprecate(
130 window,
131 key,
132 value,
133 // Deprecation notice for mw.config globals (T58550, T72470)
134 map === mw.config && 'Use mw.config instead.'
135 );
136 }
137
138 Map.prototype = {
139 /**
140 * Get the value of one or more keys.
141 *
142 * If called with no arguments, all values are returned.
143 *
144 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
145 * @param {Mixed} [fallback=null] Value for keys that don't exist.
146 * @return {Mixed|Object| null} If selection was a string, returns the value,
147 * If selection was an array, returns an object of key/values.
148 * If no selection is passed, the 'values' container is returned. (Beware that,
149 * as is the default in JavaScript, the object is returned by reference.)
150 */
151 get: function ( selection, fallback ) {
152 var results, i;
153 // If we only do this in the `return` block, it'll fail for the
154 // call to get() from the mutli-selection block.
155 fallback = arguments.length > 1 ? fallback : null;
156
157 if ( $.isArray( selection ) ) {
158 selection = slice.call( selection );
159 results = {};
160 for ( i = 0; i < selection.length; i++ ) {
161 results[ selection[ i ] ] = this.get( selection[ i ], fallback );
162 }
163 return results;
164 }
165
166 if ( typeof selection === 'string' ) {
167 if ( !hasOwn.call( this.values, selection ) ) {
168 return fallback;
169 }
170 return this.values[ selection ];
171 }
172
173 if ( selection === undefined ) {
174 return this.values;
175 }
176
177 // Invalid selection key
178 return null;
179 },
180
181 /**
182 * Set one or more key/value pairs.
183 *
184 * @param {string|Object} selection Key to set value for, or object mapping keys to values
185 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
186 * @return {boolean} True on success, false on failure
187 */
188 set: function ( selection, value ) {
189 var s;
190
191 if ( $.isPlainObject( selection ) ) {
192 for ( s in selection ) {
193 this.values[ s ] = selection[ s ];
194 }
195 return true;
196 }
197 if ( typeof selection === 'string' && arguments.length > 1 ) {
198 this.values[ selection ] = value;
199 return true;
200 }
201 return false;
202 },
203
204 /**
205 * Check if one or more keys exist.
206 *
207 * @param {Mixed} selection Key or array of keys to check
208 * @return {boolean} True if the key(s) exist
209 */
210 exists: function ( selection ) {
211 var s;
212
213 if ( $.isArray( selection ) ) {
214 for ( s = 0; s < selection.length; s++ ) {
215 if ( typeof selection[ s ] !== 'string' || !hasOwn.call( this.values, selection[ s ] ) ) {
216 return false;
217 }
218 }
219 return true;
220 }
221 return typeof selection === 'string' && hasOwn.call( this.values, selection );
222 }
223 };
224
225 /**
226 * Object constructor for messages.
227 *
228 * Similar to the Message class in MediaWiki PHP.
229 *
230 * Format defaults to 'text'.
231 *
232 * @example
233 *
234 * var obj, str;
235 * mw.messages.set( {
236 * 'hello': 'Hello world',
237 * 'hello-user': 'Hello, $1!',
238 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
239 * } );
240 *
241 * obj = new mw.Message( mw.messages, 'hello' );
242 * mw.log( obj.text() );
243 * // Hello world
244 *
245 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
246 * mw.log( obj.text() );
247 * // Hello, John Doe!
248 *
249 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
250 * mw.log( obj.text() );
251 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
252 *
253 * // Using mw.message shortcut
254 * obj = mw.message( 'hello-user', 'John Doe' );
255 * mw.log( obj.text() );
256 * // Hello, John Doe!
257 *
258 * // Using mw.msg shortcut
259 * str = mw.msg( 'hello-user', 'John Doe' );
260 * mw.log( str );
261 * // Hello, John Doe!
262 *
263 * // Different formats
264 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
265 *
266 * obj.format = 'text';
267 * str = obj.toString();
268 * // Same as:
269 * str = obj.text();
270 *
271 * mw.log( str );
272 * // Hello, John "Wiki" <3 Doe!
273 *
274 * mw.log( obj.escaped() );
275 * // Hello, John &quot;Wiki&quot; &lt;3 Doe!
276 *
277 * @class mw.Message
278 *
279 * @constructor
280 * @param {mw.Map} map Message store
281 * @param {string} key
282 * @param {Array} [parameters]
283 */
284 function Message( map, key, parameters ) {
285 this.format = 'text';
286 this.map = map;
287 this.key = key;
288 this.parameters = parameters === undefined ? [] : slice.call( parameters );
289 return this;
290 }
291
292 Message.prototype = {
293 /**
294 * Get parsed contents of the message.
295 *
296 * The default parser does simple $N replacements and nothing else.
297 * This may be overridden to provide a more complex message parser.
298 * The primary override is in the mediawiki.jqueryMsg module.
299 *
300 * This function will not be called for nonexistent messages.
301 *
302 * @return {string} Parsed message
303 */
304 parser: function () {
305 return mw.format.apply( null, [ this.map.get( this.key ) ].concat( this.parameters ) );
306 },
307
308 /**
309 * Add (does not replace) parameters for `$N` placeholder values.
310 *
311 * @param {Array} parameters
312 * @chainable
313 */
314 params: function ( parameters ) {
315 var i;
316 for ( i = 0; i < parameters.length; i++ ) {
317 this.parameters.push( parameters[ i ] );
318 }
319 return this;
320 },
321
322 /**
323 * Convert message object to its string form based on current format.
324 *
325 * @return {string} Message as a string in the current form, or `<key>` if key
326 * does not exist.
327 */
328 toString: function () {
329 var text;
330
331 if ( !this.exists() ) {
332 // Use <key> as text if key does not exist
333 if ( this.format === 'escaped' || this.format === 'parse' ) {
334 // format 'escaped' and 'parse' need to have the brackets and key html escaped
335 return mw.html.escape( '<' + this.key + '>' );
336 }
337 return '<' + this.key + '>';
338 }
339
340 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
341 text = this.parser();
342 }
343
344 if ( this.format === 'escaped' ) {
345 text = this.parser();
346 text = mw.html.escape( text );
347 }
348
349 return text;
350 },
351
352 /**
353 * Change format to 'parse' and convert message to string
354 *
355 * If jqueryMsg is loaded, this parses the message text from wikitext
356 * (where supported) to HTML
357 *
358 * Otherwise, it is equivalent to plain.
359 *
360 * @return {string} String form of parsed message
361 */
362 parse: function () {
363 this.format = 'parse';
364 return this.toString();
365 },
366
367 /**
368 * Change format to 'plain' and convert message to string
369 *
370 * This substitutes parameters, but otherwise does not change the
371 * message text.
372 *
373 * @return {string} String form of plain message
374 */
375 plain: function () {
376 this.format = 'plain';
377 return this.toString();
378 },
379
380 /**
381 * Change format to 'text' and convert message to string
382 *
383 * If jqueryMsg is loaded, {{-transformation is done where supported
384 * (such as {{plural:}}, {{gender:}}, {{int:}}).
385 *
386 * Otherwise, it is equivalent to plain
387 *
388 * @return {string} String form of text message
389 */
390 text: function () {
391 this.format = 'text';
392 return this.toString();
393 },
394
395 /**
396 * Change the format to 'escaped' and convert message to string
397 *
398 * This is equivalent to using the 'text' format (see #text), then
399 * HTML-escaping the output.
400 *
401 * @return {string} String form of html escaped message
402 */
403 escaped: function () {
404 this.format = 'escaped';
405 return this.toString();
406 },
407
408 /**
409 * Check if a message exists
410 *
411 * @see mw.Map#exists
412 * @return {boolean}
413 */
414 exists: function () {
415 return this.map.exists( this.key );
416 }
417 };
418
419 /**
420 * @class mw
421 */
422 mw = {
423
424 /**
425 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
426 *
427 * On browsers that implement the Navigation Timing API, this function will produce floating-point
428 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
429 * it will fall back to using `Date`.
430 *
431 * @return {number} Current time
432 */
433 now: ( function () {
434 var perf = window.performance,
435 navStart = perf && perf.timing && perf.timing.navigationStart;
436 return navStart && typeof perf.now === 'function' ?
437 function () { return navStart + perf.now(); } :
438 function () { return +new Date(); };
439 }() ),
440
441 /**
442 * Format a string. Replace $1, $2 ... $N with positional arguments.
443 *
444 * Used by Message#parser().
445 *
446 * @since 1.25
447 * @param {string} formatString Format string
448 * @param {...Mixed} parameters Values for $N replacements
449 * @return {string} Formatted string
450 */
451 format: function ( formatString ) {
452 var parameters = slice.call( arguments, 1 );
453 return formatString.replace( /\$(\d+)/g, function ( str, match ) {
454 var index = parseInt( match, 10 ) - 1;
455 return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
456 } );
457 },
458
459 /**
460 * Track an analytic event.
461 *
462 * This method provides a generic means for MediaWiki JavaScript code to capture state
463 * information for analysis. Each logged event specifies a string topic name that describes
464 * the kind of event that it is. Topic names consist of dot-separated path components,
465 * arranged from most general to most specific. Each path component should have a clear and
466 * well-defined purpose.
467 *
468 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
469 * events that match their subcription, including those that fired before the handler was
470 * bound.
471 *
472 * @param {string} topic Topic name
473 * @param {Object} [data] Data describing the event, encoded as an object
474 */
475 track: function ( topic, data ) {
476 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
477 trackCallbacks.fire( trackQueue );
478 },
479
480 /**
481 * Register a handler for subset of analytic events, specified by topic.
482 *
483 * Handlers will be called once for each tracked event, including any events that fired before the
484 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
485 * the exact time at which the event fired, a string 'topic' property naming the event, and a
486 * 'data' property which is an object of event-specific data. The event topic and event data are
487 * also passed to the callback as the first and second arguments, respectively.
488 *
489 * @param {string} topic Handle events whose name starts with this string prefix
490 * @param {Function} callback Handler to call for each matching tracked event
491 * @param {string} callback.topic
492 * @param {Object} [callback.data]
493 */
494 trackSubscribe: function ( topic, callback ) {
495 var seen = 0;
496 function handler( trackQueue ) {
497 var event;
498 for ( ; seen < trackQueue.length; seen++ ) {
499 event = trackQueue[ seen ];
500 if ( event.topic.indexOf( topic ) === 0 ) {
501 callback.call( event, event.topic, event.data );
502 }
503 }
504 }
505
506 trackHandlers.push( [ handler, callback ] );
507
508 trackCallbacks.add( handler );
509 },
510
511 /**
512 * Stop handling events for a particular handler
513 *
514 * @param {Function} callback
515 */
516 trackUnsubscribe: function ( callback ) {
517 trackHandlers = $.grep( trackHandlers, function ( fns ) {
518 if ( fns[ 1 ] === callback ) {
519 trackCallbacks.remove( fns[ 0 ] );
520 // Ensure the tuple is removed to avoid holding on to closures
521 return false;
522 }
523 return true;
524 } );
525 },
526
527 // Expose Map constructor
528 Map: Map,
529
530 // Expose Message constructor
531 Message: Message,
532
533 /**
534 * Map of configuration values.
535 *
536 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
537 * on mediawiki.org.
538 *
539 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
540 * global `window` object.
541 *
542 * @property {mw.Map} config
543 */
544 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
545 config: null,
546
547 /**
548 * Empty object for third-party libraries, for cases where you don't
549 * want to add a new global, or the global is bad and needs containment
550 * or wrapping.
551 *
552 * @property
553 */
554 libs: {},
555
556 /**
557 * Access container for deprecated functionality that can be moved from
558 * from their legacy location and attached to this object (e.g. a global
559 * function that is deprecated and as stop-gap can be exposed through here).
560 *
561 * This was reserved for future use but never ended up being used.
562 *
563 * @deprecated since 1.22 Let deprecated identifiers keep their original name
564 * and use mw.log#deprecate to create an access container for tracking.
565 * @property
566 */
567 legacy: {},
568
569 /**
570 * Store for messages.
571 *
572 * @property {mw.Map}
573 */
574 messages: new Map(),
575
576 /**
577 * Store for templates associated with a module.
578 *
579 * @property {mw.Map}
580 */
581 templates: new Map(),
582
583 /**
584 * Get a message object.
585 *
586 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
587 *
588 * @see mw.Message
589 * @param {string} key Key of message to get
590 * @param {...Mixed} parameters Values for $N replacements
591 * @return {mw.Message}
592 */
593 message: function ( key ) {
594 var parameters = slice.call( arguments, 1 );
595 return new Message( mw.messages, key, parameters );
596 },
597
598 /**
599 * Get a message string using the (default) 'text' format.
600 *
601 * Shortcut for `mw.message( key, parameters... ).text()`.
602 *
603 * @see mw.Message
604 * @param {string} key Key of message to get
605 * @param {...Mixed} parameters Values for $N replacements
606 * @return {string}
607 */
608 msg: function () {
609 return mw.message.apply( mw.message, arguments ).toString();
610 },
611
612 /**
613 * Dummy placeholder for {@link mw.log}
614 *
615 * @method
616 */
617 log: ( function () {
618 // Also update the restoration of methods in mediawiki.log.js
619 // when adding or removing methods here.
620 var log = function () {},
621 console = window.console;
622
623 /**
624 * @class mw.log
625 * @singleton
626 */
627
628 /**
629 * Write a message to the console's warning channel.
630 * Actions not supported by the browser console are silently ignored.
631 *
632 * @param {...string} msg Messages to output to console
633 */
634 log.warn = console && console.warn && Function.prototype.bind ?
635 Function.prototype.bind.call( console.warn, console ) :
636 $.noop;
637
638 /**
639 * Write a message to the console's error channel.
640 *
641 * Most browsers provide a stacktrace by default if the argument
642 * is a caught Error object.
643 *
644 * @since 1.26
645 * @param {Error|...string} msg Messages to output to console
646 */
647 log.error = console && console.error && Function.prototype.bind ?
648 Function.prototype.bind.call( console.error, console ) :
649 $.noop;
650
651 /**
652 * Create a property in a host object that, when accessed, will produce
653 * a deprecation warning in the console with backtrace.
654 *
655 * @param {Object} obj Host object of deprecated property
656 * @param {string} key Name of property to create in `obj`
657 * @param {Mixed} val The value this property should return when accessed
658 * @param {string} [msg] Optional text to include in the deprecation message
659 */
660 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
661 obj[ key ] = val;
662 } : function ( obj, key, val, msg ) {
663 msg = 'Use of "' + key + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
664 Object.defineProperty( obj, key, {
665 configurable: true,
666 enumerable: true,
667 get: function () {
668 mw.track( 'mw.deprecate', key );
669 mw.log.warn( msg );
670 return val;
671 },
672 set: function ( newVal ) {
673 mw.track( 'mw.deprecate', key );
674 mw.log.warn( msg );
675 val = newVal;
676 }
677 } );
678
679 };
680
681 return log;
682 }() ),
683
684 /**
685 * Client for ResourceLoader server end point.
686 *
687 * This client is in charge of maintaining the module registry and state
688 * machine, initiating network (batch) requests for loading modules, as
689 * well as dependency resolution and execution of source code.
690 *
691 * For more information, refer to
692 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
693 *
694 * @class mw.loader
695 * @singleton
696 */
697 loader: ( function () {
698
699 /**
700 * Fired via mw.track on various resource loading errors.
701 *
702 * @event resourceloader_exception
703 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
704 * object, but in theory module code could manually throw something else, and that
705 * might also end up here.
706 * @param {string} [module] Name of the module which caused the error. Omitted if the
707 * error is not module-related or the module cannot be easily identified due to
708 * batched handling.
709 * @param {string} source Source of the error. Possible values:
710 *
711 * - style: stylesheet error (only affects old IE where a special style loading method
712 * is used)
713 * - load-callback: exception thrown by user callback
714 * - module-execute: exception thrown by module code
715 * - store-eval: could not evaluate module code cached in localStorage
716 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
717 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
718 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
719 */
720
721 /**
722 * Fired via mw.track on resource loading error conditions.
723 *
724 * @event resourceloader_assert
725 * @param {string} source Source of the error. Possible values:
726 *
727 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
728 * bug; see <https://phabricator.wikimedia.org/T59567> for details
729 */
730
731 /**
732 * Mapping of registered modules.
733 *
734 * See #implement and #execute for exact details on support for script, style and messages.
735 *
736 * Format:
737 *
738 * {
739 * 'moduleName': {
740 * // From mw.loader.register()
741 * 'version': '########' (hash)
742 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
743 * 'group': 'somegroup', (or) null
744 * 'source': 'local', (or) 'anotherwiki'
745 * 'skip': 'return !!window.Example', (or) null
746 * 'module': export Object
747 *
748 * // Set from execute() or mw.loader.state()
749 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
750 *
751 * // Optionally added at run-time by mw.loader.implement()
752 * 'skipped': true
753 * 'script': closure, array of urls, or string
754 * 'style': { ... } (see #execute)
755 * 'messages': { 'key': 'value', ... }
756 * }
757 * }
758 *
759 * State machine:
760 *
761 * - `registered`:
762 * The module is known to the system but not yet requested.
763 * Meta data is registered via mw.loader#register. Calls to that method are
764 * generated server-side by the startup module.
765 * - `loading`:
766 * The module is requested through mw.loader (either directly or as dependency of
767 * another module). The client will be fetching module contents from the server.
768 * The contents are then stashed in the registry via mw.loader#implement.
769 * - `loaded`:
770 * The module has been requested from the server and stashed via mw.loader#implement.
771 * If the module has no more dependencies in-fight, the module will be executed
772 * right away. Otherwise execution is deferred, controlled via #handlePending.
773 * - `executing`:
774 * The module is being executed.
775 * - `ready`:
776 * The module has been successfully executed.
777 * - `error`:
778 * The module (or one of its dependencies) produced an error during execution.
779 * - `missing`:
780 * The module was registered client-side and requested, but the server denied knowledge
781 * of the module's existence.
782 *
783 * @property
784 * @private
785 */
786 var registry = {},
787 // Mapping of sources, keyed by source-id, values are strings.
788 //
789 // Format:
790 //
791 // {
792 // 'sourceId': 'http://example.org/w/load.php'
793 // }
794 //
795 sources = {},
796
797 // List of modules which will be loaded as when ready
798 batch = [],
799
800 // Pending queueModuleScript() requests
801 handlingPendingRequests = false,
802 pendingRequests = [],
803
804 // List of modules to be loaded
805 queue = [],
806
807 /**
808 * List of callback jobs waiting for modules to be ready.
809 *
810 * Jobs are created by #request() and run by #handlePending().
811 *
812 * Typically when a job is created for a module, the job's dependencies contain
813 * both the module being requested and all its recursive dependencies.
814 *
815 * Format:
816 *
817 * {
818 * 'dependencies': [ module names ],
819 * 'ready': Function callback
820 * 'error': Function callback
821 * }
822 *
823 * @property {Object[]} jobs
824 * @private
825 */
826 jobs = [],
827
828 // For getMarker()
829 marker = null,
830
831 // For addEmbeddedCSS()
832 cssBuffer = '',
833 cssBufferTimer = null,
834 cssCallbacks = $.Callbacks(),
835 isIE9 = document.documentMode === 9;
836
837 function getMarker() {
838 if ( !marker ) {
839 // Cache
840 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
841 if ( !marker ) {
842 mw.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
843 marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
844 }
845 }
846 return marker;
847 }
848
849 /**
850 * Create a new style element and add it to the DOM.
851 *
852 * @private
853 * @param {string} text CSS text
854 * @param {Node} [nextNode] The element where the style tag
855 * should be inserted before
856 * @return {HTMLElement} Reference to the created style element
857 */
858 function newStyleTag( text, nextNode ) {
859 var s = document.createElement( 'style' );
860
861 s.appendChild( document.createTextNode( text ) );
862 if ( nextNode && nextNode.parentNode ) {
863 nextNode.parentNode.insertBefore( s, nextNode );
864 } else {
865 document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
866 }
867
868 return s;
869 }
870
871 /**
872 * Add a bit of CSS text to the current browser page.
873 *
874 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
875 * or create a new one based on whether the given `cssText` is safe for extension.
876 *
877 * @param {string} [cssText=cssBuffer] If called without cssText,
878 * the internal buffer will be inserted instead.
879 * @param {Function} [callback]
880 */
881 function addEmbeddedCSS( cssText, callback ) {
882 var $style, styleEl;
883
884 function fireCallbacks() {
885 var oldCallbacks = cssCallbacks;
886 // Reset cssCallbacks variable so it's not polluted by any calls to
887 // addEmbeddedCSS() from one of the callbacks (T105973)
888 cssCallbacks = $.Callbacks();
889 oldCallbacks.fire().empty();
890 }
891
892 if ( callback ) {
893 cssCallbacks.add( callback );
894 }
895
896 // Yield once before creating the <style> tag. This lets multiple stylesheets
897 // accumulate into one buffer, allowing us to reduce how often new stylesheets
898 // are inserted in the browser. Appending a stylesheet and waiting for the
899 // browser to repaint is fairly expensive. (T47810)
900 if ( cssText ) {
901 // Don't extend the buffer if the item needs its own stylesheet.
902 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
903 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
904 // Linebreak for somewhat distinguishable sections
905 cssBuffer += '\n' + cssText;
906 // TODO: Using requestAnimationFrame would perform better by not injecting
907 // styles while the browser is busy painting.
908 if ( !cssBufferTimer ) {
909 cssBufferTimer = setTimeout( function () {
910 // Support: Firefox < 13
911 // Firefox 12 has non-standard behaviour of passing a number
912 // as first argument to a setTimeout callback.
913 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
914 addEmbeddedCSS();
915 } );
916 }
917 return;
918 }
919
920 // This is a scheduled flush for the buffer
921 } else {
922 cssBufferTimer = null;
923 cssText = cssBuffer;
924 cssBuffer = '';
925 }
926
927 // By default, always create a new <style>. Appending text to a <style> tag is
928 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
929 //
930 // Support: IE 6-9
931 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
932 if ( isIE9 ) {
933 $style = $( getMarker() ).prev();
934 // Verify that the element before the marker actually is a <style> tag created
935 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
936 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) ) {
937 styleEl = $style[ 0 ];
938 styleEl.appendChild( document.createTextNode( cssText ) );
939 fireCallbacks();
940 return;
941 }
942 // Else: No existing tag to reuse. Continue below and create the first one.
943 }
944
945 $style = $( newStyleTag( cssText, getMarker() ) );
946
947 if ( isIE9 ) {
948 $style.data( 'ResourceLoaderDynamicStyleTag', true );
949 }
950
951 fireCallbacks();
952 }
953
954 /**
955 * @since 1.26
956 * @param {Array} modules List of module names
957 * @return {string} Hash of concatenated version hashes.
958 */
959 function getCombinedVersion( modules ) {
960 var hashes = $.map( modules, function ( module ) {
961 return registry[ module ].version;
962 } );
963 return fnv132( hashes.join( '' ) );
964 }
965
966 /**
967 * Determine whether all dependencies are in state 'ready', which means we may
968 * execute the module or job now.
969 *
970 * @private
971 * @param {Array} modules Names of modules to be checked
972 * @return {boolean} True if all modules are in state 'ready', false otherwise
973 */
974 function allReady( modules ) {
975 var i;
976 for ( i = 0; i < modules.length; i++ ) {
977 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
978 return false;
979 }
980 }
981 return true;
982 }
983
984 /**
985 * Determine whether all dependencies are in state 'ready', which means we may
986 * execute the module or job now.
987 *
988 * @private
989 * @param {Array} modules Names of modules to be checked
990 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
991 */
992 function anyFailed( modules ) {
993 var i, state;
994 for ( i = 0; i < modules.length; i++ ) {
995 state = mw.loader.getState( modules[ i ] );
996 if ( state === 'error' || state === 'missing' ) {
997 return true;
998 }
999 }
1000 return false;
1001 }
1002
1003 /**
1004 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1005 * pending jobs and modules that depend upon this module. If the given module failed,
1006 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1007 * all jobs/modules now having their dependencies satisfied.
1008 *
1009 * Jobs that depend on a failed module, will have their error callback ran (if any).
1010 *
1011 * @private
1012 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1013 */
1014 function handlePending( module ) {
1015 var j, job, hasErrors, m, stateChange;
1016
1017 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
1018 // If the current module failed, mark all dependent modules also as failed.
1019 // Iterate until steady-state to propagate the error state upwards in the
1020 // dependency tree.
1021 do {
1022 stateChange = false;
1023 for ( m in registry ) {
1024 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
1025 if ( anyFailed( registry[ m ].dependencies ) ) {
1026 registry[ m ].state = 'error';
1027 stateChange = true;
1028 }
1029 }
1030 }
1031 } while ( stateChange );
1032 }
1033
1034 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1035 for ( j = 0; j < jobs.length; j++ ) {
1036 hasErrors = anyFailed( jobs[ j ].dependencies );
1037 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
1038 // All dependencies satisfied, or some have errors
1039 job = jobs[ j ];
1040 jobs.splice( j, 1 );
1041 j -= 1;
1042 try {
1043 if ( hasErrors ) {
1044 if ( $.isFunction( job.error ) ) {
1045 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
1046 }
1047 } else {
1048 if ( $.isFunction( job.ready ) ) {
1049 job.ready();
1050 }
1051 }
1052 } catch ( e ) {
1053 // A user-defined callback raised an exception.
1054 // Swallow it to protect our state machine!
1055 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'load-callback' } );
1056 }
1057 }
1058 }
1059
1060 if ( registry[ module ].state === 'ready' ) {
1061 // The current module became 'ready'. Set it in the module store, and recursively execute all
1062 // dependent modules that are loaded and now have all dependencies satisfied.
1063 mw.loader.store.set( module, registry[ module ] );
1064 for ( m in registry ) {
1065 if ( registry[ m ].state === 'loaded' && allReady( registry[ m ].dependencies ) ) {
1066 execute( m );
1067 }
1068 }
1069 }
1070 }
1071
1072 /**
1073 * Resolve dependencies and detect circular references.
1074 *
1075 * @private
1076 * @param {string} module Name of the top-level module whose dependencies shall be
1077 * resolved and sorted.
1078 * @param {Array} resolved Returns a topological sort of the given module and its
1079 * dependencies, such that later modules depend on earlier modules. The array
1080 * contains the module names. If the array contains already some module names,
1081 * this function appends its result to the pre-existing array.
1082 * @param {Object} [unresolved] Hash used to track the current dependency
1083 * chain; used to report loops in the dependency graph.
1084 * @throws {Error} If any unregistered module or a dependency loop is encountered
1085 */
1086 function sortDependencies( module, resolved, unresolved ) {
1087 var i, deps, skip;
1088
1089 if ( !hasOwn.call( registry, module ) ) {
1090 throw new Error( 'Unknown dependency: ' + module );
1091 }
1092
1093 if ( registry[ module ].skip !== null ) {
1094 /*jshint evil:true */
1095 skip = new Function( registry[ module ].skip );
1096 registry[ module ].skip = null;
1097 if ( skip() ) {
1098 registry[ module ].skipped = true;
1099 registry[ module ].dependencies = [];
1100 registry[ module ].state = 'ready';
1101 handlePending( module );
1102 return;
1103 }
1104 }
1105
1106 // Resolves dynamic loader function and replaces it with its own results
1107 if ( $.isFunction( registry[ module ].dependencies ) ) {
1108 registry[ module ].dependencies = registry[ module ].dependencies();
1109 // Ensures the module's dependencies are always in an array
1110 if ( typeof registry[ module ].dependencies !== 'object' ) {
1111 registry[ module ].dependencies = [ registry[ module ].dependencies ];
1112 }
1113 }
1114 if ( $.inArray( module, resolved ) !== -1 ) {
1115 // Module already resolved; nothing to do
1116 return;
1117 }
1118 // Create unresolved if not passed in
1119 if ( !unresolved ) {
1120 unresolved = {};
1121 }
1122 // Tracks down dependencies
1123 deps = registry[ module ].dependencies;
1124 for ( i = 0; i < deps.length; i++ ) {
1125 if ( $.inArray( deps[ i ], resolved ) === -1 ) {
1126 if ( unresolved[ deps[ i ] ] ) {
1127 throw new Error( mw.format(
1128 'Circular reference detected: $1 -> $2',
1129 module,
1130 deps[ i ]
1131 ) );
1132 }
1133
1134 // Add to unresolved
1135 unresolved[ module ] = true;
1136 sortDependencies( deps[ i ], resolved, unresolved );
1137 }
1138 }
1139 resolved.push( module );
1140 }
1141
1142 /**
1143 * Get names of module that a module depends on, in their proper dependency order.
1144 *
1145 * @private
1146 * @param {string[]} modules Array of string module names
1147 * @return {Array} List of dependencies, including 'module'.
1148 */
1149 function resolve( modules ) {
1150 var resolved = [];
1151 $.each( modules, function ( idx, module ) {
1152 sortDependencies( module, resolved );
1153 } );
1154 return resolved;
1155 }
1156
1157 /**
1158 * Load and execute a script.
1159 *
1160 * @private
1161 * @param {string} src URL to script, will be used as the src attribute in the script tag
1162 * @return {jQuery.Promise}
1163 */
1164 function addScript( src ) {
1165 return $.ajax( {
1166 url: src,
1167 dataType: 'script',
1168 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1169 // XHR for a same domain request instead of <script>, which changes the request
1170 // headers (potentially missing a cache hit), and reduces caching in general
1171 // since browsers cache XHR much less (if at all). And XHR means we retreive
1172 // text, so we'd need to $.globalEval, which then messes up line numbers.
1173 crossDomain: true,
1174 cache: true
1175 } );
1176 }
1177
1178 /**
1179 * Queue the loading and execution of a script for a particular module.
1180 *
1181 * @private
1182 * @param {string} src URL of the script
1183 * @param {string} [moduleName] Name of currently executing module
1184 * @return {jQuery.Promise}
1185 */
1186 function queueModuleScript( src, moduleName ) {
1187 var r = $.Deferred();
1188
1189 pendingRequests.push( function () {
1190 if ( moduleName && hasOwn.call( registry, moduleName ) ) {
1191 window.require = mw.loader.require;
1192 window.module = registry[ moduleName ].module;
1193 }
1194 addScript( src ).always( function () {
1195 // Clear environment
1196 delete window.require;
1197 delete window.module;
1198 r.resolve();
1199
1200 // Start the next one (if any)
1201 if ( pendingRequests[ 0 ] ) {
1202 pendingRequests.shift()();
1203 } else {
1204 handlingPendingRequests = false;
1205 }
1206 } );
1207 } );
1208 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1209 handlingPendingRequests = true;
1210 pendingRequests.shift()();
1211 }
1212 return r.promise();
1213 }
1214
1215 /**
1216 * Utility function for execute()
1217 *
1218 * @ignore
1219 */
1220 function addLink( media, url ) {
1221 var el = document.createElement( 'link' );
1222
1223 el.rel = 'stylesheet';
1224 if ( media && media !== 'all' ) {
1225 el.media = media;
1226 }
1227 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1228 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1229 el.href = url;
1230
1231 $( getMarker() ).before( el );
1232 }
1233
1234 /**
1235 * Executes a loaded module, making it ready to use
1236 *
1237 * @private
1238 * @param {string} module Module name to execute
1239 */
1240 function execute( module ) {
1241 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1242 cssHandlesRegistered = false;
1243
1244 if ( !hasOwn.call( registry, module ) ) {
1245 throw new Error( 'Module has not been registered yet: ' + module );
1246 }
1247 if ( registry[ module ].state !== 'loaded' ) {
1248 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1249 }
1250
1251 registry[ module ].state = 'executing';
1252
1253 runScript = function () {
1254 var script, markModuleReady, nestedAddScript, legacyWait,
1255 // Expand to include dependencies since we have to exclude both legacy modules
1256 // and their dependencies from the legacyWait (to prevent a circular dependency).
1257 legacyModules = resolve( mw.config.get( 'wgResourceLoaderLegacyModules', [] ) );
1258 try {
1259 script = registry[ module ].script;
1260 markModuleReady = function () {
1261 registry[ module ].state = 'ready';
1262 handlePending( module );
1263 };
1264 nestedAddScript = function ( arr, callback, i ) {
1265 // Recursively call queueModuleScript() in its own callback
1266 // for each element of arr.
1267 if ( i >= arr.length ) {
1268 // We're at the end of the array
1269 callback();
1270 return;
1271 }
1272
1273 queueModuleScript( arr[ i ], module ).always( function () {
1274 nestedAddScript( arr, callback, i + 1 );
1275 } );
1276 };
1277
1278 legacyWait = ( $.inArray( module, legacyModules ) !== -1 )
1279 ? $.Deferred().resolve()
1280 : mw.loader.using( legacyModules );
1281
1282 legacyWait.always( function () {
1283 if ( $.isArray( script ) ) {
1284 nestedAddScript( script, markModuleReady, 0 );
1285 } else if ( $.isFunction( script ) ) {
1286 // Pass jQuery twice so that the signature of the closure which wraps
1287 // the script can bind both '$' and 'jQuery'.
1288 script( $, $, mw.loader.require, registry[ module ].module );
1289 markModuleReady();
1290
1291 } else if ( typeof script === 'string' ) {
1292 // Site and user modules are legacy scripts that run in the global scope.
1293 // This is transported as a string instead of a function to avoid needing
1294 // to use string manipulation to undo the function wrapper.
1295 if ( module === 'user' ) {
1296 // Implicit dependency on the site module. Not real dependency because
1297 // it should run after 'site' regardless of whether it succeeds or fails.
1298 mw.loader.using( 'site' ).always( function () {
1299 $.globalEval( script );
1300 markModuleReady();
1301 } );
1302 } else {
1303 $.globalEval( script );
1304 markModuleReady();
1305 }
1306 } else {
1307 // Module without script
1308 markModuleReady();
1309 }
1310 } );
1311 } catch ( e ) {
1312 // This needs to NOT use mw.log because these errors are common in production mode
1313 // and not in debug mode, such as when a symbol that should be global isn't exported
1314 registry[ module ].state = 'error';
1315 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'module-execute' } );
1316 handlePending( module );
1317 }
1318 };
1319
1320 // Add localizations to message system
1321 if ( registry[ module ].messages ) {
1322 mw.messages.set( registry[ module ].messages );
1323 }
1324
1325 // Initialise templates
1326 if ( registry[ module ].templates ) {
1327 mw.templates.set( module, registry[ module ].templates );
1328 }
1329
1330 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1331 ( function () {
1332 var pending = 0;
1333 checkCssHandles = function () {
1334 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1335 // one of the cssHandles is fired while we're still creating more handles.
1336 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1337 runScript();
1338 runScript = undefined; // Revoke
1339 }
1340 };
1341 cssHandle = function () {
1342 var check = checkCssHandles;
1343 pending++;
1344 return function () {
1345 if ( check ) {
1346 pending--;
1347 check();
1348 check = undefined; // Revoke
1349 }
1350 };
1351 };
1352 }() );
1353
1354 // Process styles (see also mw.loader.implement)
1355 // * back-compat: { <media>: css }
1356 // * back-compat: { <media>: [url, ..] }
1357 // * { "css": [css, ..] }
1358 // * { "url": { <media>: [url, ..] } }
1359 if ( registry[ module ].style ) {
1360 for ( key in registry[ module ].style ) {
1361 value = registry[ module ].style[ key ];
1362 media = undefined;
1363
1364 if ( key !== 'url' && key !== 'css' ) {
1365 // Backwards compatibility, key is a media-type
1366 if ( typeof value === 'string' ) {
1367 // back-compat: { <media>: css }
1368 // Ignore 'media' because it isn't supported (nor was it used).
1369 // Strings are pre-wrapped in "@media". The media-type was just ""
1370 // (because it had to be set to something).
1371 // This is one of the reasons why this format is no longer used.
1372 addEmbeddedCSS( value, cssHandle() );
1373 } else {
1374 // back-compat: { <media>: [url, ..] }
1375 media = key;
1376 key = 'bc-url';
1377 }
1378 }
1379
1380 // Array of css strings in key 'css',
1381 // or back-compat array of urls from media-type
1382 if ( $.isArray( value ) ) {
1383 for ( i = 0; i < value.length; i++ ) {
1384 if ( key === 'bc-url' ) {
1385 // back-compat: { <media>: [url, ..] }
1386 addLink( media, value[ i ] );
1387 } else if ( key === 'css' ) {
1388 // { "css": [css, ..] }
1389 addEmbeddedCSS( value[ i ], cssHandle() );
1390 }
1391 }
1392 // Not an array, but a regular object
1393 // Array of urls inside media-type key
1394 } else if ( typeof value === 'object' ) {
1395 // { "url": { <media>: [url, ..] } }
1396 for ( media in value ) {
1397 urls = value[ media ];
1398 for ( i = 0; i < urls.length; i++ ) {
1399 addLink( media, urls[ i ] );
1400 }
1401 }
1402 }
1403 }
1404 }
1405
1406 // Kick off.
1407 cssHandlesRegistered = true;
1408 checkCssHandles();
1409 }
1410
1411 /**
1412 * Adds all dependencies to the queue with optional callbacks to be run
1413 * when the dependencies are ready or fail
1414 *
1415 * @private
1416 * @param {string|string[]} dependencies Module name or array of string module names
1417 * @param {Function} [ready] Callback to execute when all dependencies are ready
1418 * @param {Function} [error] Callback to execute when any dependency fails
1419 */
1420 function request( dependencies, ready, error ) {
1421 // Allow calling by single module name
1422 if ( typeof dependencies === 'string' ) {
1423 dependencies = [ dependencies ];
1424 }
1425
1426 // Add ready and error callbacks if they were given
1427 if ( ready !== undefined || error !== undefined ) {
1428 jobs.push( {
1429 // Narrow down the list to modules that are worth waiting for
1430 dependencies: $.grep( dependencies, function ( module ) {
1431 var state = mw.loader.getState( module );
1432 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1433 } ),
1434 ready: ready,
1435 error: error
1436 } );
1437 }
1438
1439 $.each( dependencies, function ( idx, module ) {
1440 var state = mw.loader.getState( module );
1441 // Only queue modules that are still in the initial 'registered' state
1442 // (not ones already loading, ready or error).
1443 if ( state === 'registered' && $.inArray( module, queue ) === -1 ) {
1444 // Private modules must be embedded in the page. Don't bother queuing
1445 // these as the server will deny them anyway (T101806).
1446 if ( registry[ module ].group === 'private' ) {
1447 registry[ module ].state = 'error';
1448 handlePending( module );
1449 return;
1450 }
1451 queue.push( module );
1452 }
1453 } );
1454
1455 mw.loader.work();
1456 }
1457
1458 function sortQuery( o ) {
1459 var key,
1460 sorted = {},
1461 a = [];
1462
1463 for ( key in o ) {
1464 if ( hasOwn.call( o, key ) ) {
1465 a.push( key );
1466 }
1467 }
1468 a.sort();
1469 for ( key = 0; key < a.length; key++ ) {
1470 sorted[ a[ key ] ] = o[ a[ key ] ];
1471 }
1472 return sorted;
1473 }
1474
1475 /**
1476 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1477 * to a query string of the form foo.bar,baz|bar.baz,quux
1478 *
1479 * @private
1480 */
1481 function buildModulesString( moduleMap ) {
1482 var p, prefix,
1483 arr = [];
1484
1485 for ( prefix in moduleMap ) {
1486 p = prefix === '' ? '' : prefix + '.';
1487 arr.push( p + moduleMap[ prefix ].join( ',' ) );
1488 }
1489 return arr.join( '|' );
1490 }
1491
1492 /**
1493 * Load modules from load.php
1494 *
1495 * @private
1496 * @param {Object} moduleMap Module map, see #buildModulesString
1497 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1498 * @param {string} sourceLoadScript URL of load.php
1499 */
1500 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
1501 var request = $.extend(
1502 { modules: buildModulesString( moduleMap ) },
1503 currReqBase
1504 );
1505 request = sortQuery( request );
1506 addScript( sourceLoadScript + '?' + $.param( request ) );
1507 }
1508
1509 /**
1510 * Resolve indexed dependencies.
1511 *
1512 * ResourceLoader uses an optimization to save space which replaces module names in
1513 * dependency lists with the index of that module within the array of module
1514 * registration data if it exists. The benefit is a significant reduction in the data
1515 * size of the startup module. This function changes those dependency lists back to
1516 * arrays of strings.
1517 *
1518 * @param {Array} modules Modules array
1519 */
1520 function resolveIndexedDependencies( modules ) {
1521 $.each( modules, function ( idx, module ) {
1522 if ( module[ 2 ] ) {
1523 module[ 2 ] = $.map( module[ 2 ], function ( dep ) {
1524 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1525 } );
1526 }
1527 } );
1528 }
1529
1530 /* Public Members */
1531 return {
1532 /**
1533 * The module registry is exposed as an aid for debugging and inspecting page
1534 * state; it is not a public interface for modifying the registry.
1535 *
1536 * @see #registry
1537 * @property
1538 * @private
1539 */
1540 moduleRegistry: registry,
1541
1542 /**
1543 * @inheritdoc #newStyleTag
1544 * @method
1545 */
1546 addStyleTag: newStyleTag,
1547
1548 /**
1549 * Batch-request queued dependencies from the server.
1550 */
1551 work: function () {
1552 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1553 source, concatSource, origBatch, group, i, modules, sourceLoadScript,
1554 currReqBase, currReqBaseLength, moduleMap, l,
1555 lastDotIndex, prefix, suffix, bytesAdded;
1556
1557 // Build a list of request parameters common to all requests.
1558 reqBase = {
1559 skin: mw.config.get( 'skin' ),
1560 lang: mw.config.get( 'wgUserLanguage' ),
1561 debug: mw.config.get( 'debug' )
1562 };
1563 // Split module batch by source and by group.
1564 splits = {};
1565 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1566
1567 // Appends a list of modules from the queue to the batch
1568 for ( q = 0; q < queue.length; q++ ) {
1569 // Only request modules which are registered
1570 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1571 // Prevent duplicate entries
1572 if ( $.inArray( queue[ q ], batch ) === -1 ) {
1573 batch.push( queue[ q ] );
1574 // Mark registered modules as loading
1575 registry[ queue[ q ] ].state = 'loading';
1576 }
1577 }
1578 }
1579
1580 mw.loader.store.init();
1581 if ( mw.loader.store.enabled ) {
1582 concatSource = [];
1583 origBatch = batch;
1584 batch = $.grep( batch, function ( module ) {
1585 var source = mw.loader.store.get( module );
1586 if ( source ) {
1587 concatSource.push( source );
1588 return false;
1589 }
1590 return true;
1591 } );
1592 try {
1593 $.globalEval( concatSource.join( ';' ) );
1594 } catch ( err ) {
1595 // Not good, the cached mw.loader.implement calls failed! This should
1596 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1597 // Depending on how corrupt the string is, it is likely that some
1598 // modules' implement() succeeded while the ones after the error will
1599 // never run and leave their modules in the 'loading' state forever.
1600
1601 // Since this is an error not caused by an individual module but by
1602 // something that infected the implement call itself, don't take any
1603 // risks and clear everything in this cache.
1604 mw.loader.store.clear();
1605 // Re-add the ones still pending back to the batch and let the server
1606 // repopulate these modules to the cache.
1607 // This means that at most one module will be useless (the one that had
1608 // the error) instead of all of them.
1609 mw.track( 'resourceloader.exception', { exception: err, source: 'store-eval' } );
1610 origBatch = $.grep( origBatch, function ( module ) {
1611 return registry[ module ].state === 'loading';
1612 } );
1613 batch = batch.concat( origBatch );
1614 }
1615 }
1616
1617 // Early exit if there's nothing to load...
1618 if ( !batch.length ) {
1619 return;
1620 }
1621
1622 // The queue has been processed into the batch, clear up the queue.
1623 queue = [];
1624
1625 // Always order modules alphabetically to help reduce cache
1626 // misses for otherwise identical content.
1627 batch.sort();
1628
1629 // Split batch by source and by group.
1630 for ( b = 0; b < batch.length; b++ ) {
1631 bSource = registry[ batch[ b ] ].source;
1632 bGroup = registry[ batch[ b ] ].group;
1633 if ( !hasOwn.call( splits, bSource ) ) {
1634 splits[ bSource ] = {};
1635 }
1636 if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1637 splits[ bSource ][ bGroup ] = [];
1638 }
1639 bSourceGroup = splits[ bSource ][ bGroup ];
1640 bSourceGroup.push( batch[ b ] );
1641 }
1642
1643 // Clear the batch - this MUST happen before we append any
1644 // script elements to the body or it's possible that a script
1645 // will be locally cached, instantly load, and work the batch
1646 // again, all before we've cleared it causing each request to
1647 // include modules which are already loaded.
1648 batch = [];
1649
1650 for ( source in splits ) {
1651
1652 sourceLoadScript = sources[ source ];
1653
1654 for ( group in splits[ source ] ) {
1655
1656 // Cache access to currently selected list of
1657 // modules for this group from this source.
1658 modules = splits[ source ][ group ];
1659
1660 currReqBase = $.extend( {
1661 version: getCombinedVersion( modules )
1662 }, reqBase );
1663 // For user modules append a user name to the request.
1664 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1665 currReqBase.user = mw.config.get( 'wgUserName' );
1666 }
1667 currReqBaseLength = $.param( currReqBase ).length;
1668 // We may need to split up the request to honor the query string length limit,
1669 // so build it piece by piece.
1670 l = currReqBaseLength + 9; // '&modules='.length == 9
1671
1672 moduleMap = {}; // { prefix: [ suffixes ] }
1673
1674 for ( i = 0; i < modules.length; i++ ) {
1675 // Determine how many bytes this module would add to the query string
1676 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1677
1678 // If lastDotIndex is -1, substr() returns an empty string
1679 prefix = modules[ i ].substr( 0, lastDotIndex );
1680 suffix = modules[ i ].slice( lastDotIndex + 1 );
1681
1682 bytesAdded = hasOwn.call( moduleMap, prefix )
1683 ? suffix.length + 3 // '%2C'.length == 3
1684 : modules[ i ].length + 3; // '%7C'.length == 3
1685
1686 // If the request would become too long, create a new one,
1687 // but don't create empty requests
1688 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1689 // This request would become too long, create a new one
1690 // and fire off the old one
1691 doRequest( moduleMap, currReqBase, sourceLoadScript );
1692 moduleMap = {};
1693 l = currReqBaseLength + 9;
1694 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1695 }
1696 if ( !hasOwn.call( moduleMap, prefix ) ) {
1697 moduleMap[ prefix ] = [];
1698 }
1699 moduleMap[ prefix ].push( suffix );
1700 l += bytesAdded;
1701 }
1702 // If there's anything left in moduleMap, request that too
1703 if ( !$.isEmptyObject( moduleMap ) ) {
1704 doRequest( moduleMap, currReqBase, sourceLoadScript );
1705 }
1706 }
1707 }
1708 },
1709
1710 /**
1711 * Register a source.
1712 *
1713 * The #work() method will use this information to split up requests by source.
1714 *
1715 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1716 *
1717 * @param {string|Object} id Source ID, or object mapping ids to load urls
1718 * @param {string} loadUrl Url to a load.php end point
1719 * @throws {Error} If source id is already registered
1720 */
1721 addSource: function ( id, loadUrl ) {
1722 var source;
1723 // Allow multiple additions
1724 if ( typeof id === 'object' ) {
1725 for ( source in id ) {
1726 mw.loader.addSource( source, id[ source ] );
1727 }
1728 return;
1729 }
1730
1731 if ( hasOwn.call( sources, id ) ) {
1732 throw new Error( 'source already registered: ' + id );
1733 }
1734
1735 sources[ id ] = loadUrl;
1736 },
1737
1738 /**
1739 * Register a module, letting the system know about it and its properties.
1740 *
1741 * The startup modules contain calls to this method.
1742 *
1743 * When using multiple module registration by passing an array, dependencies that
1744 * are specified as references to modules within the array will be resolved before
1745 * the modules are registered.
1746 *
1747 * @param {string|Array} module Module name or array of arrays, each containing
1748 * a list of arguments compatible with this method
1749 * @param {string|number} version Module version hash (falls backs to empty string)
1750 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1751 * @param {string|Array|Function} dependencies One string or array of strings of module
1752 * names on which this module depends, or a function that returns that array.
1753 * @param {string} [group=null] Group which the module is in
1754 * @param {string} [source='local'] Name of the source
1755 * @param {string} [skip=null] Script body of the skip function
1756 */
1757 register: function ( module, version, dependencies, group, source, skip ) {
1758 var i;
1759 // Allow multiple registration
1760 if ( typeof module === 'object' ) {
1761 resolveIndexedDependencies( module );
1762 for ( i = 0; i < module.length; i++ ) {
1763 // module is an array of module names
1764 if ( typeof module[ i ] === 'string' ) {
1765 mw.loader.register( module[ i ] );
1766 // module is an array of arrays
1767 } else if ( typeof module[ i ] === 'object' ) {
1768 mw.loader.register.apply( mw.loader, module[ i ] );
1769 }
1770 }
1771 return;
1772 }
1773 if ( hasOwn.call( registry, module ) ) {
1774 throw new Error( 'module already registered: ' + module );
1775 }
1776 // List the module as registered
1777 registry[ module ] = {
1778 // Exposed to execute() for mw.loader.implement() closures.
1779 // Import happens via require().
1780 module: {
1781 exports: {}
1782 },
1783 version: version !== undefined ? String( version ) : '',
1784 dependencies: [],
1785 group: typeof group === 'string' ? group : null,
1786 source: typeof source === 'string' ? source : 'local',
1787 state: 'registered',
1788 skip: typeof skip === 'string' ? skip : null
1789 };
1790 if ( typeof dependencies === 'string' ) {
1791 // Allow dependencies to be given as a single module name
1792 registry[ module ].dependencies = [ dependencies ];
1793 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1794 // Allow dependencies to be given as an array of module names
1795 // or a function which returns an array
1796 registry[ module ].dependencies = dependencies;
1797 }
1798 },
1799
1800 /**
1801 * Implement a module given the components that make up the module.
1802 *
1803 * When #load or #using requests one or more modules, the server
1804 * response contain calls to this function.
1805 *
1806 * @param {string} module Name of module
1807 * @param {Function|Array} [script] Function with module code or Array of URLs to
1808 * be used as the src attribute of a new `<script>` tag.
1809 * @param {Object} [style] Should follow one of the following patterns:
1810 *
1811 * { "css": [css, ..] }
1812 * { "url": { <media>: [url, ..] } }
1813 *
1814 * And for backwards compatibility (needs to be supported forever due to caching):
1815 *
1816 * { <media>: css }
1817 * { <media>: [url, ..] }
1818 *
1819 * The reason css strings are not concatenated anymore is bug 31676. We now check
1820 * whether it's safe to extend the stylesheet.
1821 *
1822 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1823 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1824 */
1825 implement: function ( module, script, style, messages, templates ) {
1826 // Automatically register module
1827 if ( !hasOwn.call( registry, module ) ) {
1828 mw.loader.register( module );
1829 }
1830 // Check for duplicate implementation
1831 if ( hasOwn.call( registry, module ) && registry[ module ].script !== undefined ) {
1832 throw new Error( 'module already implemented: ' + module );
1833 }
1834 // Attach components
1835 registry[ module ].script = script || null;
1836 registry[ module ].style = style || null;
1837 registry[ module ].messages = messages || null;
1838 registry[ module ].templates = templates || null;
1839 // The module may already have been marked as erroneous
1840 if ( $.inArray( registry[ module ].state, [ 'error', 'missing' ] ) === -1 ) {
1841 registry[ module ].state = 'loaded';
1842 if ( allReady( registry[ module ].dependencies ) ) {
1843 execute( module );
1844 }
1845 }
1846 },
1847
1848 /**
1849 * Execute a function as soon as one or more required modules are ready.
1850 *
1851 * Example of inline dependency on OOjs:
1852 *
1853 * mw.loader.using( 'oojs', function () {
1854 * OO.compare( [ 1 ], [ 1 ] );
1855 * } );
1856 *
1857 * @param {string|Array} dependencies Module name or array of modules names the
1858 * callback depends on to be ready before executing
1859 * @param {Function} [ready] Callback to execute when all dependencies are ready
1860 * @param {Function} [error] Callback to execute if one or more dependencies failed
1861 * @return {jQuery.Promise}
1862 * @since 1.23 this returns a promise
1863 */
1864 using: function ( dependencies, ready, error ) {
1865 var deferred = $.Deferred();
1866
1867 // Allow calling with a single dependency as a string
1868 if ( typeof dependencies === 'string' ) {
1869 dependencies = [ dependencies ];
1870 }
1871
1872 if ( ready ) {
1873 deferred.done( ready );
1874 }
1875 if ( error ) {
1876 deferred.fail( error );
1877 }
1878
1879 // Resolve entire dependency map
1880 dependencies = resolve( dependencies );
1881 if ( allReady( dependencies ) ) {
1882 // Run ready immediately
1883 deferred.resolve();
1884 } else if ( anyFailed( dependencies ) ) {
1885 // Execute error immediately if any dependencies have errors
1886 deferred.reject(
1887 new Error( 'One or more dependencies failed to load' ),
1888 dependencies
1889 );
1890 } else {
1891 // Not all dependencies are ready: queue up a request
1892 request( dependencies, deferred.resolve, deferred.reject );
1893 }
1894
1895 return deferred.promise();
1896 },
1897
1898 /**
1899 * Load an external script or one or more modules.
1900 *
1901 * @param {string|Array} modules Either the name of a module, array of modules,
1902 * or a URL of an external script or style
1903 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1904 * external script or style; acceptable values are "text/css" and
1905 * "text/javascript"; if no type is provided, text/javascript is assumed.
1906 */
1907 load: function ( modules, type ) {
1908 var filtered, l;
1909
1910 // Allow calling with a url or single dependency as a string
1911 if ( typeof modules === 'string' ) {
1912 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1913 if ( /^(https?:)?\/?\//.test( modules ) ) {
1914 if ( type === 'text/css' ) {
1915 // Support: IE 7-8
1916 // Use properties instead of attributes as IE throws security
1917 // warnings when inserting a <link> tag with a protocol-relative
1918 // URL set though attributes - when on HTTPS. See bug 41331.
1919 l = document.createElement( 'link' );
1920 l.rel = 'stylesheet';
1921 l.href = modules;
1922 $( 'head' ).append( l );
1923 return;
1924 }
1925 if ( type === 'text/javascript' || type === undefined ) {
1926 addScript( modules );
1927 return;
1928 }
1929 // Unknown type
1930 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1931 }
1932 // Called with single module
1933 modules = [ modules ];
1934 }
1935
1936 // Filter out undefined modules, otherwise resolve() will throw
1937 // an exception for trying to load an undefined module.
1938 // Undefined modules are acceptable here in load(), because load() takes
1939 // an array of unrelated modules, whereas the modules passed to
1940 // using() are related and must all be loaded.
1941 filtered = $.grep( modules, function ( module ) {
1942 var state = mw.loader.getState( module );
1943 return state !== null && state !== 'error' && state !== 'missing';
1944 } );
1945
1946 if ( filtered.length === 0 ) {
1947 return;
1948 }
1949 // Resolve entire dependency map
1950 filtered = resolve( filtered );
1951 // If all modules are ready, or if any modules have errors, nothing to be done.
1952 if ( allReady( filtered ) || anyFailed( filtered ) ) {
1953 return;
1954 }
1955 // Since some modules are not yet ready, queue up a request.
1956 request( filtered, undefined, undefined );
1957 },
1958
1959 /**
1960 * Change the state of one or more modules.
1961 *
1962 * @param {string|Object} module Module name or object of module name/state pairs
1963 * @param {string} state State name
1964 */
1965 state: function ( module, state ) {
1966 var m;
1967
1968 if ( typeof module === 'object' ) {
1969 for ( m in module ) {
1970 mw.loader.state( m, module[ m ] );
1971 }
1972 return;
1973 }
1974 if ( !hasOwn.call( registry, module ) ) {
1975 mw.loader.register( module );
1976 }
1977 if ( $.inArray( state, [ 'ready', 'error', 'missing' ] ) !== -1
1978 && registry[ module ].state !== state ) {
1979 // Make sure pending modules depending on this one get executed if their
1980 // dependencies are now fulfilled!
1981 registry[ module ].state = state;
1982 handlePending( module );
1983 } else {
1984 registry[ module ].state = state;
1985 }
1986 },
1987
1988 /**
1989 * Get the version of a module.
1990 *
1991 * @param {string} module Name of module
1992 * @return {string|null} The version, or null if the module (or its version) is not
1993 * in the registry.
1994 */
1995 getVersion: function ( module ) {
1996 if ( !hasOwn.call( registry, module ) || registry[ module ].version === undefined ) {
1997 return null;
1998 }
1999 return registry[ module ].version;
2000 },
2001
2002 /**
2003 * Get the state of a module.
2004 *
2005 * @param {string} module Name of module
2006 * @return {string|null} The state, or null if the module (or its state) is not
2007 * in the registry.
2008 */
2009 getState: function ( module ) {
2010 if ( !hasOwn.call( registry, module ) || registry[ module ].state === undefined ) {
2011 return null;
2012 }
2013 return registry[ module ].state;
2014 },
2015
2016 /**
2017 * Get the names of all registered modules.
2018 *
2019 * @return {Array}
2020 */
2021 getModuleNames: function () {
2022 return $.map( registry, function ( i, key ) {
2023 return key;
2024 } );
2025 },
2026
2027 /**
2028 * Get the exported value of a module.
2029 *
2030 * Module provide this value via their local `module.exports`.
2031 *
2032 * @since 1.27
2033 * @return {Array}
2034 */
2035 require: function ( moduleName ) {
2036 var state = mw.loader.getState( moduleName );
2037
2038 // Only ready modules can be required
2039 if ( state !== 'ready' ) {
2040 // Module may've forgotten to declare a dependency
2041 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
2042 }
2043
2044 return registry[ moduleName ].module.exports;
2045 },
2046
2047 /**
2048 * @inheritdoc mw.inspect#runReports
2049 * @method
2050 */
2051 inspect: function () {
2052 var args = slice.call( arguments );
2053 mw.loader.using( 'mediawiki.inspect', function () {
2054 mw.inspect.runReports.apply( mw.inspect, args );
2055 } );
2056 },
2057
2058 /**
2059 * On browsers that implement the localStorage API, the module store serves as a
2060 * smart complement to the browser cache. Unlike the browser cache, the module store
2061 * can slice a concatenated response from ResourceLoader into its constituent
2062 * modules and cache each of them separately, using each module's versioning scheme
2063 * to determine when the cache should be invalidated.
2064 *
2065 * @singleton
2066 * @class mw.loader.store
2067 */
2068 store: {
2069 // Whether the store is in use on this page.
2070 enabled: null,
2071
2072 MODULE_SIZE_MAX: 100 * 1000,
2073
2074 // The contents of the store, mapping '[module name]@[version]' keys
2075 // to module implementations.
2076 items: {},
2077
2078 // Cache hit stats
2079 stats: { hits: 0, misses: 0, expired: 0 },
2080
2081 /**
2082 * Construct a JSON-serializable object representing the content of the store.
2083 *
2084 * @return {Object} Module store contents.
2085 */
2086 toJSON: function () {
2087 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2088 },
2089
2090 /**
2091 * Get the localStorage key for the entire module store. The key references
2092 * $wgDBname to prevent clashes between wikis which share a common host.
2093 *
2094 * @return {string} localStorage item key
2095 */
2096 getStoreKey: function () {
2097 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2098 },
2099
2100 /**
2101 * Get a key on which to vary the module cache.
2102 *
2103 * @return {string} String of concatenated vary conditions.
2104 */
2105 getVary: function () {
2106 return [
2107 mw.config.get( 'skin' ),
2108 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2109 mw.config.get( 'wgUserLanguage' )
2110 ].join( ':' );
2111 },
2112
2113 /**
2114 * Get a key for a specific module. The key format is '[name]@[version]'.
2115 *
2116 * @param {string} module Module name
2117 * @return {string|null} Module key or null if module does not exist
2118 */
2119 getModuleKey: function ( module ) {
2120 return hasOwn.call( registry, module ) ?
2121 ( module + '@' + registry[ module ].version ) : null;
2122 },
2123
2124 /**
2125 * Initialize the store.
2126 *
2127 * Retrieves store from localStorage and (if successfully retrieved) decoding
2128 * the stored JSON value to a plain object.
2129 *
2130 * The try / catch block is used for JSON & localStorage feature detection.
2131 * See the in-line documentation for Modernizr's localStorage feature detection
2132 * code for a full account of why we need a try / catch:
2133 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2134 */
2135 init: function () {
2136 var raw, data;
2137
2138 if ( mw.loader.store.enabled !== null ) {
2139 // Init already ran
2140 return;
2141 }
2142
2143 if (
2144 // Disabled because localStorage quotas are tight and (in Firefox's case)
2145 // shared by multiple origins.
2146 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2147 /Firefox|Opera/.test( navigator.userAgent ) ||
2148
2149 // Disabled by configuration.
2150 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2151 ) {
2152 // Clear any previous store to free up space. (T66721)
2153 mw.loader.store.clear();
2154 mw.loader.store.enabled = false;
2155 return;
2156 }
2157 if ( mw.config.get( 'debug' ) ) {
2158 // Disable module store in debug mode
2159 mw.loader.store.enabled = false;
2160 return;
2161 }
2162
2163 try {
2164 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2165 // If we get here, localStorage is available; mark enabled
2166 mw.loader.store.enabled = true;
2167 data = JSON.parse( raw );
2168 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2169 mw.loader.store.items = data.items;
2170 return;
2171 }
2172 } catch ( e ) {
2173 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-init' } );
2174 }
2175
2176 if ( raw === undefined ) {
2177 // localStorage failed; disable store
2178 mw.loader.store.enabled = false;
2179 } else {
2180 mw.loader.store.update();
2181 }
2182 },
2183
2184 /**
2185 * Retrieve a module from the store and update cache hit stats.
2186 *
2187 * @param {string} module Module name
2188 * @return {string|boolean} Module implementation or false if unavailable
2189 */
2190 get: function ( module ) {
2191 var key;
2192
2193 if ( !mw.loader.store.enabled ) {
2194 return false;
2195 }
2196
2197 key = mw.loader.store.getModuleKey( module );
2198 if ( key in mw.loader.store.items ) {
2199 mw.loader.store.stats.hits++;
2200 return mw.loader.store.items[ key ];
2201 }
2202 mw.loader.store.stats.misses++;
2203 return false;
2204 },
2205
2206 /**
2207 * Stringify a module and queue it for storage.
2208 *
2209 * @param {string} module Module name
2210 * @param {Object} descriptor The module's descriptor as set in the registry
2211 */
2212 set: function ( module, descriptor ) {
2213 var args, key, src;
2214
2215 if ( !mw.loader.store.enabled ) {
2216 return false;
2217 }
2218
2219 key = mw.loader.store.getModuleKey( module );
2220
2221 if (
2222 // Already stored a copy of this exact version
2223 key in mw.loader.store.items ||
2224 // Module failed to load
2225 descriptor.state !== 'ready' ||
2226 // Unversioned, private, or site-/user-specific
2227 ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user' ] ) !== -1 ) ||
2228 // Partial descriptor
2229 $.inArray( undefined, [ descriptor.script, descriptor.style,
2230 descriptor.messages, descriptor.templates ] ) !== -1
2231 ) {
2232 // Decline to store
2233 return false;
2234 }
2235
2236 try {
2237 args = [
2238 JSON.stringify( module ),
2239 typeof descriptor.script === 'function' ?
2240 String( descriptor.script ) :
2241 JSON.stringify( descriptor.script ),
2242 JSON.stringify( descriptor.style ),
2243 JSON.stringify( descriptor.messages ),
2244 JSON.stringify( descriptor.templates )
2245 ];
2246 // Attempted workaround for a possible Opera bug (bug T59567).
2247 // This regex should never match under sane conditions.
2248 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2249 args[ 1 ] = 'function' + args[ 1 ];
2250 mw.track( 'resourceloader.assert', { source: 'bug-T59567' } );
2251 }
2252 } catch ( e ) {
2253 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-json' } );
2254 return;
2255 }
2256
2257 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2258 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2259 return false;
2260 }
2261 mw.loader.store.items[ key ] = src;
2262 mw.loader.store.update();
2263 },
2264
2265 /**
2266 * Iterate through the module store, removing any item that does not correspond
2267 * (in name and version) to an item in the module registry.
2268 */
2269 prune: function () {
2270 var key, module;
2271
2272 if ( !mw.loader.store.enabled ) {
2273 return false;
2274 }
2275
2276 for ( key in mw.loader.store.items ) {
2277 module = key.slice( 0, key.indexOf( '@' ) );
2278 if ( mw.loader.store.getModuleKey( module ) !== key ) {
2279 mw.loader.store.stats.expired++;
2280 delete mw.loader.store.items[ key ];
2281 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2282 // This value predates the enforcement of a size limit on cached modules.
2283 delete mw.loader.store.items[ key ];
2284 }
2285 }
2286 },
2287
2288 /**
2289 * Clear the entire module store right now.
2290 */
2291 clear: function () {
2292 mw.loader.store.items = {};
2293 try {
2294 localStorage.removeItem( mw.loader.store.getStoreKey() );
2295 } catch ( ignored ) {}
2296 },
2297
2298 /**
2299 * Sync in-memory store back to localStorage.
2300 *
2301 * This function debounces updates. When called with a flush already pending,
2302 * the call is coalesced into the pending update. The call to
2303 * localStorage.setItem will be naturally deferred until the page is quiescent.
2304 *
2305 * Because localStorage is shared by all pages from the same origin, if multiple
2306 * pages are loaded with different module sets, the possibility exists that
2307 * modules saved by one page will be clobbered by another. But the impact would
2308 * be minor and the problem would be corrected by subsequent page views.
2309 *
2310 * @method
2311 */
2312 update: ( function () {
2313 var hasPendingWrite = false;
2314
2315 function flushWrites() {
2316 var data, key;
2317 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2318 return;
2319 }
2320
2321 mw.loader.store.prune();
2322 key = mw.loader.store.getStoreKey();
2323 try {
2324 // Replacing the content of the module store might fail if the new
2325 // contents would exceed the browser's localStorage size limit. To
2326 // avoid clogging the browser with stale data, always remove the old
2327 // value before attempting to set the new one.
2328 localStorage.removeItem( key );
2329 data = JSON.stringify( mw.loader.store );
2330 localStorage.setItem( key, data );
2331 } catch ( e ) {
2332 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-update' } );
2333 }
2334
2335 hasPendingWrite = false;
2336 }
2337
2338 return function () {
2339 if ( !hasPendingWrite ) {
2340 hasPendingWrite = true;
2341 mw.requestIdleCallback( flushWrites );
2342 }
2343 };
2344 }() )
2345 }
2346 };
2347 }() ),
2348
2349 /**
2350 * HTML construction helper functions
2351 *
2352 * @example
2353 *
2354 * var Html, output;
2355 *
2356 * Html = mw.html;
2357 * output = Html.element( 'div', {}, new Html.Raw(
2358 * Html.element( 'img', { src: '<' } )
2359 * ) );
2360 * mw.log( output ); // <div><img src="&lt;"/></div>
2361 *
2362 * @class mw.html
2363 * @singleton
2364 */
2365 html: ( function () {
2366 function escapeCallback( s ) {
2367 switch ( s ) {
2368 case '\'':
2369 return '&#039;';
2370 case '"':
2371 return '&quot;';
2372 case '<':
2373 return '&lt;';
2374 case '>':
2375 return '&gt;';
2376 case '&':
2377 return '&amp;';
2378 }
2379 }
2380
2381 return {
2382 /**
2383 * Escape a string for HTML.
2384 *
2385 * Converts special characters to HTML entities.
2386 *
2387 * mw.html.escape( '< > \' & "' );
2388 * // Returns &lt; &gt; &#039; &amp; &quot;
2389 *
2390 * @param {string} s The string to escape
2391 * @return {string} HTML
2392 */
2393 escape: function ( s ) {
2394 return s.replace( /['"<>&]/g, escapeCallback );
2395 },
2396
2397 /**
2398 * Create an HTML element string, with safe escaping.
2399 *
2400 * @param {string} name The tag name.
2401 * @param {Object} [attrs] An object with members mapping element names to values
2402 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2403 *
2404 * - string: Text to be escaped.
2405 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2406 * - this.Raw: The raw value is directly included.
2407 * - this.Cdata: The raw value is directly included. An exception is
2408 * thrown if it contains any illegal ETAGO delimiter.
2409 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2410 * @return {string} HTML
2411 */
2412 element: function ( name, attrs, contents ) {
2413 var v, attrName, s = '<' + name;
2414
2415 if ( attrs ) {
2416 for ( attrName in attrs ) {
2417 v = attrs[ attrName ];
2418 // Convert name=true, to name=name
2419 if ( v === true ) {
2420 v = attrName;
2421 // Skip name=false
2422 } else if ( v === false ) {
2423 continue;
2424 }
2425 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2426 }
2427 }
2428 if ( contents === undefined || contents === null ) {
2429 // Self close tag
2430 s += '/>';
2431 return s;
2432 }
2433 // Regular open tag
2434 s += '>';
2435 switch ( typeof contents ) {
2436 case 'string':
2437 // Escaped
2438 s += this.escape( contents );
2439 break;
2440 case 'number':
2441 case 'boolean':
2442 // Convert to string
2443 s += String( contents );
2444 break;
2445 default:
2446 if ( contents instanceof this.Raw ) {
2447 // Raw HTML inclusion
2448 s += contents.value;
2449 } else if ( contents instanceof this.Cdata ) {
2450 // CDATA
2451 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2452 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2453 }
2454 s += contents.value;
2455 } else {
2456 throw new Error( 'mw.html.element: Invalid type of contents' );
2457 }
2458 }
2459 s += '</' + name + '>';
2460 return s;
2461 },
2462
2463 /**
2464 * Wrapper object for raw HTML passed to mw.html.element().
2465 *
2466 * @class mw.html.Raw
2467 */
2468 Raw: function ( value ) {
2469 this.value = value;
2470 },
2471
2472 /**
2473 * Wrapper object for CDATA element contents passed to mw.html.element()
2474 *
2475 * @class mw.html.Cdata
2476 */
2477 Cdata: function ( value ) {
2478 this.value = value;
2479 }
2480 };
2481 }() ),
2482
2483 // Skeleton user object, extended by the 'mediawiki.user' module.
2484 /**
2485 * @class mw.user
2486 * @singleton
2487 */
2488 user: {
2489 /**
2490 * @property {mw.Map}
2491 */
2492 options: new Map(),
2493 /**
2494 * @property {mw.Map}
2495 */
2496 tokens: new Map()
2497 },
2498
2499 // OOUI widgets specific to MediaWiki
2500 widgets: {},
2501
2502 /**
2503 * Registry and firing of events.
2504 *
2505 * MediaWiki has various interface components that are extended, enhanced
2506 * or manipulated in some other way by extensions, gadgets and even
2507 * in core itself.
2508 *
2509 * This framework helps streamlining the timing of when these other
2510 * code paths fire their plugins (instead of using document-ready,
2511 * which can and should be limited to firing only once).
2512 *
2513 * Features like navigating to other wiki pages, previewing an edit
2514 * and editing itself – without a refresh – can then retrigger these
2515 * hooks accordingly to ensure everything still works as expected.
2516 *
2517 * Example usage:
2518 *
2519 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2520 * mw.hook( 'wikipage.content' ).fire( $content );
2521 *
2522 * Handlers can be added and fired for arbitrary event names at any time. The same
2523 * event can be fired multiple times. The last run of an event is memorized
2524 * (similar to `$(document).ready` and `$.Deferred().done`).
2525 * This means if an event is fired, and a handler added afterwards, the added
2526 * function will be fired right away with the last given event data.
2527 *
2528 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2529 * Thus allowing flexible use and optimal maintainability and authority control.
2530 * You can pass around the `add` and/or `fire` method to another piece of code
2531 * without it having to know the event name (or `mw.hook` for that matter).
2532 *
2533 * var h = mw.hook( 'bar.ready' );
2534 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2535 *
2536 * Note: Events are documented with an underscore instead of a dot in the event
2537 * name due to jsduck not supporting dots in that position.
2538 *
2539 * @class mw.hook
2540 */
2541 hook: ( function () {
2542 var lists = {};
2543
2544 /**
2545 * Create an instance of mw.hook.
2546 *
2547 * @method hook
2548 * @member mw
2549 * @param {string} name Name of hook.
2550 * @return {mw.hook}
2551 */
2552 return function ( name ) {
2553 var list = hasOwn.call( lists, name ) ?
2554 lists[ name ] :
2555 lists[ name ] = $.Callbacks( 'memory' );
2556
2557 return {
2558 /**
2559 * Register a hook handler
2560 *
2561 * @param {...Function} handler Function to bind.
2562 * @chainable
2563 */
2564 add: list.add,
2565
2566 /**
2567 * Unregister a hook handler
2568 *
2569 * @param {...Function} handler Function to unbind.
2570 * @chainable
2571 */
2572 remove: list.remove,
2573
2574 /**
2575 * Run a hook.
2576 *
2577 * @param {...Mixed} data
2578 * @chainable
2579 */
2580 fire: function () {
2581 return list.fireWith.call( this, null, slice.call( arguments ) );
2582 }
2583 };
2584 };
2585 }() )
2586 };
2587
2588 // Alias $j to jQuery for backwards compatibility
2589 // @deprecated since 1.23 Use $ or jQuery instead
2590 mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
2591
2592 /**
2593 * Log a message to window.console, if possible.
2594 *
2595 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2596 * also in production mode). Gets console references in each invocation instead of caching the
2597 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2598 *
2599 * @private
2600 * @method log_
2601 * @param {string} topic Stream name passed by mw.track
2602 * @param {Object} data Data passed by mw.track
2603 * @param {Error} [data.exception]
2604 * @param {string} data.source Error source
2605 * @param {string} [data.module] Name of module which caused the error
2606 */
2607 function log( topic, data ) {
2608 var msg,
2609 e = data.exception,
2610 source = data.source,
2611 module = data.module,
2612 console = window.console;
2613
2614 if ( console && console.log ) {
2615 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
2616 if ( module ) {
2617 msg += ' in module ' + module;
2618 }
2619 msg += ( e ? ':' : '.' );
2620 console.log( msg );
2621
2622 // If we have an exception object, log it to the error channel to trigger
2623 // proper stacktraces in browsers that support it. No fallback as we have
2624 // no browsers that don't support error(), but do support log().
2625 if ( e && console.error ) {
2626 console.error( String( e ), e );
2627 }
2628 }
2629 }
2630
2631 // Subscribe to error streams
2632 mw.trackSubscribe( 'resourceloader.exception', log );
2633 mw.trackSubscribe( 'resourceloader.assert', log );
2634
2635 /**
2636 * Fired when all modules associated with the page have finished loading.
2637 *
2638 * @event resourceloader_loadEnd
2639 * @member mw.hook
2640 */
2641 $( function () {
2642 var loading = $.grep( mw.loader.getModuleNames(), function ( module ) {
2643 return mw.loader.getState( module ) === 'loading';
2644 } );
2645 // In order to use jQuery.when (which stops early if one of the promises got rejected)
2646 // cast any loading failures into successes. We only need a callback, not the module.
2647 loading = $.map( loading, function ( module ) {
2648 return mw.loader.using( module ).then( null, function () {
2649 return $.Deferred().resolve();
2650 } );
2651 } );
2652 $.when.apply( $, loading ).then( function () {
2653 mwPerformance.mark( 'mwLoadEnd' );
2654 mw.hook( 'resourceloader.loadEnd' ).fire();
2655 } );
2656 } );
2657
2658 // Attach to window and globally alias
2659 window.mw = window.mediaWiki = mw;
2660 }( jQuery ) );